<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Services\BaoliaoDataSyncService;

class MigrateBaoliaoToShardedTables extends Command
{
    protected $signature = 'baoliao:migrate-to-sharded 
                            {--chunk=1000 : 每次处理的记录数量}';
    protected $description = '将爆料帖子数据迁移到分表';
    
    public function handle()
    {
        $baseTable = 'baoliao_post';
        $chunkSize = $this->option('chunk');
        
        // 检查分表是否存在
        $hotTablesExist = DB::select("SHOW TABLES LIKE '{$baseTable}_hot_%'");
        $timeTablesExist = DB::select("SHOW TABLES LIKE '{$baseTable}_20%'");
        
        if (empty($hotTablesExist) && empty($timeTablesExist)) {
            $this->error('没有找到任何分表，请先运行 baoliao:create-sharded-tables 命令创建分表');
            return;
        }
        
        $total = DB::table($baseTable)->count();
        $bar = $this->output->createProgressBar($total);
        
        $syncService = app(BaoliaoDataSyncService::class);
        
        $this->info('开始迁移数据到分表...');
        
        // 分批处理数据
        DB::table($baseTable)->orderBy('id')->chunk($chunkSize, function ($posts) use ($syncService, $bar) {
            foreach ($posts as $post) {
                try {
                    $syncService->syncToShardedTables($post);
                    $bar->advance();
                } catch (\Exception $e) {
                    $this->error("迁移帖子 {$post->id} 失败: " . $e->getMessage());
                }
            }
        });
        
        $bar->finish();
        $this->info("\n数据迁移完成");
    }
}
